import {
  wxRequest
} from '../../utils/server.js';

const _wxRequest = new wxRequest();
const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    listStatus: false, //宫格为false 列表为ture
    adList: [],
    headlineList: [],
    imgUrl: app.globalData.imgUrl,
    hasNextPage: false,
    uploadUrl: wx.getStorageSync('uploadUrl'),
    list: [],
    pageNo: 1,
    tabId: 1,
    keyword: '',
    sortType: 1,
    stoSortType: 1,
    hotCity: false,
    catId:'',
    userInfo:wx.getStorageSync('userInfo')||''
  },

  onShow: function() {
    this.getlist();
    this.findAdPicture()
    this.getSelfLocation();
    this.findOpenCity('东莞市')
    if (!wx.getStorageSync('loacaltionCity')) {
      this.setData({
        hotCity: true
      })
    }

    if (wx.getStorageSync('Authorization')){ 
      this.infoList();
    } 
  },


  //筛选
  handleFilt: function(e) {
    var sortType = e.currentTarget.dataset.type;
    this.setData({
      sortType
    })
    this.getlist()
  },


  //店铺筛选
  handleStoreFilt: function(e) {
    var stoSortType = e.currentTarget.dataset.type;
    this.setData({
      stoSortType: stoSortType
    })
    this.getlist()
  },


  // tab切换
  checkTab(e) {
    var id = e.currentTarget.dataset.id
    this.setData({
      tabId: id,
      pageNo: 1,
      hasNextPage: false, //初始化 
      catflag: false,
      catId:''
    })
   
    this.getlist()
  },

  //跳转详情页
  toGoodsDetail(e) {
    var id = e.currentTarget.dataset.id
    console.log(e)
    wx.navigateTo({
      url: '/pages/good/detail/index?id=' + id,
    })
  },

  toStoreDetail(e) {
    var id = e.currentTarget.dataset.id
    console.log(e)
    wx.navigateTo({
      url: '/pages/store/detail?id=' + id,
    })
  },


  tosearch: function() {
    if (!wx.getStorageSync('Authorization')){
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return
    }

    wx.navigateTo({
      url: '/pages/index/component/search',
    })
  },


  //价格筛选
  handlePice() {
    var sortType = this.data.sortType;
    if (sortType == 4) {
      sortType = 5
    } else {
      sortType = 4
    }
    console.log(sortType, 'sortType')
    this.setData({
      sortType
    })
    this.getlist()
  },

  handletype() {
    this.setData({
      listStatus: !this.data.listStatus
    })
  },



  //查询列表
  getlist: function() {
    if (this.data.tabId == 1) {
      this.goodsRequest()
    } else {
      this.storeRequest()
    }
  },


  //商品请求
  goodsRequest: function() {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/gds/goods/list?keyword=' + this.data.keyword + '&sortType=' + this.data.sortType + '&catId=' + this.data.catId + '&pageNo=' + this.data.pageNo,
      method: 'POST'
    }, (res) => {
      let list = res.list;
      if (this.data.pageNo !== 1) {
        list = this.data.list.concat(list);
      }

      this.setData({
        list: list,
        pageNo: res.page.pageNo,
        hasNextPage: res.page.hasNextPage,
      });
    })
  },


  //店铺请求
  storeRequest: function() {
    this.setData({
      list:[]
     })

    if (!this.data.selfLongitude || !this.data.selfLongitude) {
      this.setData({
        storeflage: true
      })
      this.getuserLocation();
    }

    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/org/protected/store/findList',
      method: 'POST',
      // contentType: 'application/x-www-form-urlencoded',
      data: {
        pageNo: this.data.pageNo,
        keyword: this.data.keyword,
        sortType: this.data.stoSortType,
        lng: this.data.selfLongitude || '', //经度
        lat: this.data.selfLatitude || '', //纬度 
        cityId: wx.getStorageSync('loacaltionCity').code || ''
      }
    }, (res) => {

      let list = res.list;

      if (list.length > 0) {
        if (this.data.pageNo !== 1) {
          list = this.data.list.concat(list);
        }
        list.map(item => {
          item.offInfoJson = JSON.parse(item.offInfoJson);
          item.content = item.content.trim()
          if (item.distance >= 1000) {
            item.distanceText = (item.distance / 1000).toFixed(1) + 'km'
          } else if (item.distance > 0) {
            item.distanceText = Math.ceil(item.distance) + 'm'
          } else {
            item.distanceText = '未知'
          }
        })
  
        this.setData({
          list: list,
          pageNo: res.page.pageNo,
          hasNextPage: res.page.hasNextPage,
        });
      }

    })
  },


  //下拉刷新
  onPullDownRefresh: function() {
    this.refreshData();
    this.findAdPicture()
    this.infoList()
    wx.stopPullDownRefresh()
  },

  refreshData: function() {
    this.setData({
      pageNo: 1
    })
    this.getlist();
  },

  //触底时，加载更多
  onReachBottom: function() {
    if (this.data.hasNextPage) {
      this.setData({
        pageNo: this.data.pageNo + 1
      });
      this.getlist();
    }
  },


  //查询广告
  findAdPicture: function() {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/sys/ad/findAdPicture',
      method: 'POST',
      data: {
        keyword: this.data.keyword,
      }
    }, (res) => {
      let adList = res.list;
      this.setData({
        adList
      })
    })
  },


  //推荐活动/资讯
  infoList: function() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/sys/protected/info/list',
      method: 'POST',
      data: {
        cityId: wx.getStorageSync('loacaltionCity').code || ''
      }
    }, (res) => {
      let headlineList = res.list;
      this.setData({
        headlineList
      })
    })
  },

  //分享
  onShareAppMessage: function() {

  },

  getSelfLocation: function() {
    var that = this;
    //用户授权过可以直接获取位置
    wx.getLocation({
      type: 'wgs84',
      // type: 'gcj02',
      success: function(res) {
        var latitude = res.latitude;
        var longitude = res.longitude;
        console.log(res, 'res')
        that.setData({
          selfLongitude: longitude, //经度
          selfLatitude: latitude, //纬度        
        });
        that.getcityName()
      },
      fail: function(res) {
        setTimeout(function() {
          that.getuserLocation()
        }, 1000);
      }
    });
  },


  //需要用户授权获取位置
  getuserLocation: function() {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          wx.openSetting({
            success: (response) => {
              wx.getLocation({
                success: function(res) {
                  var latitude = res.latitude;
                  var longitude = res.longitude;
                  that.setData({
                    selfLongitude: longitude, //经度
                    selfLatitude: latitude, //纬度        
                  });
                  that.getcityName()
                  if (that.data.storeflage) {
                    that.storeRequest()
                  }
                }
              })
            }
          })
        }
      }
    })
  },

  //根据经纬度获取城市名称
  getcityName: function() {
    var that = this
    wx.request({
      url: "https://apis.map.qq.com/ws/geocoder/v1/?location=" + that.data.selfLatitude + "," + that.data.selfLongitude + "&key=OINBZ-X6GCV-T2IPD-UUYQS-NDAKE-2DBRP",
      success: function(result) {
        console.log(result.data.result)
        var res = result.data.result
        if (res && res.address_component) {
          that.setData({
            cityName: res.address_component.city
          })
          that.findOpenCity(res.address_component.city);
        }

      }
    })
  },

  //平台支持的城市列表
  findOpenCity: function(cityName) {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/sys/district/findOpenCity',
      method: 'POST',
      data: {
        cityName
      }
    }, (res) => {
      console.log(res, 'res')
      this.setData({
        defaultCity: res.defaultCity,
        cityList: res.list
      })
    })
  },

  //选择城市
  checkCity: function(e) {
    var item = e.currentTarget.dataset.item;
    wx.setStorageSync('loacaltionCity', item)
    this.setData({
      loacaltionCity: item,
      hotCity: false
    })
    this.getlist(); 

    if (wx.getStorageSync('userInfo')) {  
      this.infoList();
      this.updataCustomer()
    }


  },

  //更换城市
  changeCity: function() {
    var userInfor = wx.getStorageSync('userInfo');
    if (!userInfor) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return
    }

    this.setData({
      hotCity: true
    })

  },

  //更新客户信息
  updataCustomer: function() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + "/odr/protected/customer/update",
      method: 'POST',
      data: {
        id: wx.getStorageSync('userInfo').id,
        focusCityId: this.data.loacaltionCity.code,
        focusCity: this.data.loacaltionCity.cityName
      }
    }, (res) => {
      console.log(res, '更新')
    })
  },

  // 分类
  handleCat:function(e){
    var that=this;
    var sortType = e.currentTarget.dataset.type;
    this.setData({
      catflag:true,
      sortType
    })
     
    that.getCat()
  },

getCat:function(){
  _wxRequest.wxAjax({
    url: app.globalData.apiUrl + "/gds/goods/findGoodsCat",
    method: 'POST',
    data:{} 
  }, (res) => {
    console.log(res, '分类')
    this.setData({
      catlist:res.list
    }) 
  })
},
//选择分类
  handleCatItem:function(e){
    var code = e.currentTarget.dataset.code;
    this.setData({
      catId:code,
      catflag: false,
    })
    this.getlist()
  }








})